package com.itheima.sh.h_json_case;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

@WebServlet("/jsonDemo03Servlet")
public class JsonDemo03Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    //3.请求是json字符串，响应数据改成json字符串
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //从前端获取json数据
            //Friend friend = JSON.parseObject(request.getInputStream(), Friend.class);
            Friend friend = BaseController.jsonToBean(request, Friend.class);
            System.out.println("friend = " + friend);
            //创建List集合存储好友数据，并传到前端
            ArrayList<Friend> list = new ArrayList<>();
            Collections.addAll(list, new Friend(1, "吴亦凡", 28)
                    , new Friend(2, "李易峰", 30), new Friend(3, "李云迪", 32)
                    , new Friend(4, "张三", 18), new Friend(5, "李四", 34));
            //转化成Json字符串
            //int i = 1/0;
            Result result = new Result(true, "数据响应成功！", list);
            //调用方法
            BaseController.sendJsonToBrowser(response, result);
            //String str = JSON.toJSONString(result);
            //response.getWriter().write(str);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                //如果出现异常，返回flase和提示信息
                Result result = new Result(false, "数据响应失败！！！");
                //调用方法
                BaseController.sendJsonToBrowser(response, result);
            } catch (Exception exception) {
                exception.printStackTrace();
            }

        }

    }
}